﻿using System;
using System.Text;

namespace 数据编码和数据流_1
{
    class Program
    {
        static StringBuilder sb = new StringBuilder();
        static void Main(string[] args)
        {
            string s = string.Empty;
            Random r = new Random();
            for (int i = 0; i < 3; i++)
            {
                s += r.Next(0, 100) + " ";
            }
            sb.AppendLine("被编码的字符串：" + s);
            sb.AppendLine("------------------------------------");
            EncodeDecode(s, Encoding.Unicode);
            EncodeDecode(s, Encoding.BigEndianUnicode);
            EncodeDecode(s, Encoding.UTF8);
            EncodeDecode(s, Encoding.Default);
            EncodeDecode(s, Encoding.ASCII);
            EncodeDecode(s, Encoding.UTF32);
            EncodeDecode(s, Encoding.UTF7);
            TransForm(Encoding.UTF8, Encoding.Unicode, s);
            Console.WriteLine(sb);
            Console.ReadKey();
        }

        private static void EncodeDecode(string str, Encoding encoding)
        {
            //将字符串编码为字节数组
            byte[] bytes = encoding.GetBytes(str);
            //将字节数组解码为字符串
            string decodestr = encoding.GetString(bytes);
            //编码对应的字节数组对应的十六进制输出
            string encodeResult = BitConverter.ToString(bytes);
            sb.AppendFormat("编码为: {0}, 编码结果: {1} \n", encoding.EncodingName, encodeResult);
            sb.AppendFormat("解码结果: {0}\n", decodestr);
            sb.AppendLine("------------------------");

        }

        private static void TransForm(Encoding srcEncoding, Encoding dstEncoding, string s)
        {
            byte[] b1 = srcEncoding.GetBytes(s);
            byte[] b2 = Encoding.Convert(srcEncoding, dstEncoding, b1);
            Console.WriteLine("将{0}编码转换为{1}编码的字符串: {2} ", srcEncoding.HeaderName, dstEncoding.HeaderName, dstEncoding.GetString(b2));
            Console.WriteLine("--------");
        }


    }
}
